import React, { useEffect } from 'react';
import { Button, DatePicker, Select, Space, Spin } from 'antd';
import _ from 'lodash';
import moment from 'moment';

import { useTRState } from '#/utils/trHooks.jsx';
import { TjSegmented, TjChart } from '@/pages/ETrade/components';
import { priceComparisonBeforeAndAfterCorrection } from '../../services.js';
import styles from './index.less';
import { getCssVariableValue } from '@/utils/utils';
import { useThemeChange } from '@/hooks';

const getDateRange = () => {
  return [moment().add(-3, 'day'), moment().add(-1, 'day')];
};

const _SERIES = [
  {
    dataIndex: 'provincialDayaheadClearingPriceUnadjusted',
    type: 'line',
    name: '日前价格-修正前',
    color: '#5E92F6',
  },
  {
    dataIndex: 'provincialDayaheadClearingPrice',
    type: 'dashed',
    name: '日前价格-修正后',
    color: '#5E92F6',
  },
  {
    dataIndex: 'provincialRealtimeClearingPriceUnadjusted',
    type: 'line',
    name: '实时价格-修正前',
    color: '#E86452',
  },
  {
    dataIndex: 'provincialRealtimeClearingPrice',
    type: 'dashed',
    name: '实时价格-修正后',
    color: '#E86452',
  },
];

export default ({ power }) => {
  const [state, setState] = useTRState({
    formValue: {}, // 已用表单
    // form
    dates: getDateRange(),
    marketItem: {}, // 交易中心信息
    stationItem: {}, // 交易单元信息
    stationOptions: [], // 交易单元
    pointKey: 'ninetySixMap',
    // result
    loading: true,
    dataSource: [],
    chartData: {},
  });
  const { theme } = useThemeChange();

  useEffect(() => {
    onChangeMarket(power[0], 'search');
  }, []);

  const getAllStation = (data) => _.flattenDeep(data?.map((a) => a?.children));

  const onChangeMarket = (marketItem, type) => {
    // 交易中心改变
    const stationOptions = getAllStation(marketItem?.children || []);
    state.marketItem = marketItem;
    state.stationItem = stationOptions?.[0] || {};
    if (marketItem.marketId === 'PDBLJ') {
      setState({
        pointKey: '96',
        marketItem,
        stationOptions,
        stationItem: state.stationItem,
        formValue: {
          marketId: state.marketItem.value,
        },
      });
    } else {
      setState({
        pointKey: 'ninetySixMap',
        marketItem,
        stationOptions,
        stationItem: state.stationItem,
        formValue: {
          marketId: state.marketItem.value,
        },
      });
    }
    if (type === 'search') {
      _onFinish();
    }
  };

  const _onFinish = async (isReset) => {
    let formValue = {};
    if (isReset === true) {
      formValue = {
        startDate: getDateRange()[0].format('YYYY-MM-DD'),
        endDate: getDateRange()[1].format('YYYY-MM-DD'),
        provinceId: state.marketItem.provinceId,
        marketId: state.marketItem.value,
        stationIds: [state.stationItem.value],
        type: state.marketItem.value === 'PDBLJ' ? '96' : 'ninetySixMap',
      };
    } else {
      formValue = {
        startDate: state.dates[0].format('YYYY-MM-DD'),
        endDate: state.dates[1].format('YYYY-MM-DD'),
        provinceId: state.marketItem.provinceId,
        marketId: state.marketItem.value,
        stationIds: [state.stationItem.value],
        type: state.pointKey,
      };
    }
    // 查询
    setState({
      formValue,
      loading: true,
    });
    const res = await priceComparisonBeforeAndAfterCorrection(formValue);
    if (formValue.marketId === 'PDBLJ') {
      state.dataSource = res?.data?.data || [];
    } else {
      state.dataSource = res?.data?.dataCompareMap || [];
    }
    setState({
      dataSource: state.dataSource,
      loading: false,
    });
  };

  const _onReset = () => {
    // 重置
    setState({
      dates: getDateRange(),
    });
    onChangeMarket(power[0]);
    _onFinish(true);
  };

  /**
   * 将原始电价数据转换为结构化格式
   * @param {Object} inputData - 原始数据对象
   * @param {string[]} inputData.xAxis - 时间轴数组（格式：["YYYYMMDD HHmm", ...]）
   * @param {string[]} inputData.dayAheadList - 日前出清电价
   * @param {string[]} inputData.dayAheadUnAdjustList - 日前出清电价(未调整)
   * @param {string[]} inputData.realtimeList - 实时出清电价
   * @param {string[]} inputData.realtimeUnAdjustList - 实时出清电价(未调整)
   * @param {number} stationId - 场站ID
   * @param {string} stationName - 场站名称
   * @returns {Object[]} 结构化后的数据数组
   */
  const transformPriceData = (inputData) => {
    return inputData.xAxis.map((datetimeStr, index) => {
      return {
        provincialDayaheadClearingPriceUnadjusted: _.isNil(inputData.dayAheadUnAdjustList[index])
          ? '-'
          : _.round(Number(inputData.dayAheadUnAdjustList[index]), 2).toFixed(2),
        provincialDayaheadClearingPrice: _.isNil(inputData.dayAheadList[index])
          ? '-'
          : _.round(Number(inputData.dayAheadList[index]), 2).toFixed(2),
        provincialRealtimeClearingPriceUnadjusted: _.isNil(inputData.realtimeUnAdjustList[index])
          ? '-'
          : _.round(Number(inputData.realtimeUnAdjustList[index]), 2).toFixed(2),
        provincialRealtimeClearingPrice: _.isNil(inputData.realtimeList[index])
          ? '-'
          : _.round(Number(inputData.realtimeList[index]), 2).toFixed(2),
        datetime: datetimeStr,
      };
    });
  };

  /** renders */
  const getChartOption = () => {
    let chartData = [];
    if (state.formValue.marketId !== 'PDBLJ') {
      state.dataSource.map((x) => {
        const dataMap = x?.[state.pointKey];
        const stationId = Object.keys(dataMap)[0];
        dataMap[stationId].map((dataItem) => {
          let temp = {};
          const datetime = moment(`${dataItem.date} ${dataItem.xAxis}`).format('YYYYMMDD HHmm');
          for (const k in dataItem) {
            temp[k] = dataItem[k];
            if (k !== 'stationId' && k !== 'timeOrder' && typeof temp[k] === 'number') {
              temp[k] = temp[k].toFixed(2);
            }
          }
          chartData.push({
            ...temp,
            datetime,
          });
        });
      });
    } else {
      chartData = transformPriceData(state.dataSource);
    }

    return {
      grid: { top: 48, left: 48, right: 0, bottom: 50 },
      series: _SERIES,
      dataset: {
        source: chartData,
        dimensions: ['datetime', ..._SERIES.map((x) => x.dataIndex)],
      },
      tooltip: {
        formatter: (params) => {
          const { datetime, ...values } = params[0].data;
          const space = '4px';
          return `<div style="color:#7A7D7F;margin-bottom:${space};">${datetime}</div>
                  <div style="display:flex;">
                    <div style="color:#D3D4D4;">
                      <div style="margin-bottom:${space};">修正前</div>
                      <div>修正后</div>
                    </div>
                    <div style="color:#7A7D7F;margin:0 8px 0 16px;">
                      <div style="margin-bottom:${space};">日前价格</div>
                      <div>日前价格</div>
                    </div>
                    <div style="color:#5E92F6;text-align:right;">
                      <div style="margin-bottom:${space};">${values.provincialDayaheadClearingPriceUnadjusted}</div>
                      <div>${values.provincialDayaheadClearingPrice}</div>
                    </div>
                    <div style="color:#7A7D7F;margin:0 8px 0 16px;">
                      <div style="margin-bottom:${space};">实时价格</div>
                      <div>实时价格</div>
                    </div>
                    <div style="color:#E86452;text-align:right;">
                      <div style="margin-bottom:${space};">${values.provincialRealtimeClearingPriceUnadjusted}</div>
                      <div>${values.provincialRealtimeClearingPrice}</div>
                    </div>
                  </div>`;
        },
      },
      legend: {
        textStyle: {
          color: getCssVariableValue('--chart-legend-color'),
        },
      },
      xAxis: [
        {
          type: 'category',
          formatter: (v) => v.slice(4),
          axisLabel: {
            color: getCssVariableValue('--chart-font-color'),
          },
          axisLine: {
            lineStyle: {
              type: 'solid',
              color: getCssVariableValue('--chart-x-line'),
            },
          },
          axisTick: {
            lineStyle: {
              color: getCssVariableValue('--chart-y-line'),
            },
          },
          axisPointer: {
            type: 'line',
            lineStyle: {
              color: getCssVariableValue('--chart-x-line'),
            },
          },
        },
      ],
      yAxis: [
        {
          type: 'value',
          name: '元/MWh',
          axisLabel: {
            color: getCssVariableValue('--chart-font-color'),
          },
          axisTick: {
            lineStyle: {
              color: getCssVariableValue('--chart-y-line'),
            },
          },
          splitLine: {
            lineStyle: {
              color: getCssVariableValue('--chart-y-line'),
            },
          },
        },
      ],
    };
  };

  useEffect(() => {
    setTimeout(() => {
      const chartData = getChartOption();
      setState({ chartData });
    }, 1);
  }, [state.dataSource, theme]);

  return (
    <>
      <div className={styles.head}>
        <Space size={16} wrap>
          <Select
            style={{ width: 200 }}
            value={state.marketItem.value}
            options={power}
            optionFilterProp="label"
            showSearch
            showArrow
            onChange={(v, option) => onChangeMarket(option)}
            getPopupContainer={(e) => e.parentNode}
          />
          <DatePicker.RangePicker
            style={{ width: 216 }}
            value={state.dates}
            separator="-"
            format={'YYYYMMDD'}
            disabledDate={(v) => v > moment()}
            allowClear={false}
            onChange={(dates) => setState({ dates })}
            getPopupContainer={(e) => e.parentNode}
          />
          <Select
            style={{ width: 200 }}
            value={state.stationItem.value}
            options={state.stationOptions}
            optionFilterProp="label"
            showSearch
            showArrow
            onChange={(v, stationItem) => setState({ stationItem })}
            getPopupContainer={(e) => e.parentNode}
          />
          <TjSegmented
            value={state.pointKey}
            options={[
              { label: '24', value: state.formValue.marketId === 'PDBLJ' ? '24' : 'twentyFourMap' },
              { label: '96', value: state.formValue.marketId === 'PDBLJ' ? '96' : 'ninetySixMap' },
            ]}
            onChange={(pointKey) => setState({ pointKey })}
          />
          <Space size={16}>
            <Button
              style={{ width: 98, height: 32 }}
              type="primary"
              disabled={state.loading}
              onClick={_onFinish}
            >
              查询
            </Button>
            <Button style={{ width: 98, height: 32 }} ghost onClick={_onReset}>
              重置
            </Button>
          </Space>
        </Space>
      </div>
      <div className={styles.main}>
        <Spin spinning={state.loading}>
          <TjChart option={state.chartData} style={{ height: 350 }} />
        </Spin>
      </div>
    </>
  );
};
